package com.damai.http;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.HttpsURLConnection;

import com.citywithincity.utils.HttpsUtil;

public class Https {

	
	
	public static HttpURLConnection createConnection(Request request) throws IOException{
		
		String url = request.getUrl();
		String encoding = request.getEncoding();
		
		URL postUrl = new URL(url);
		HttpURLConnection connection = null;
		if(url.startsWith("https")){
			HttpsURLConnection httpsURLConnection = (HttpsURLConnection) postUrl.openConnection();
			HttpsUtil.setConnections(httpsURLConnection);
			connection = httpsURLConnection;
		}else{
			connection = (HttpURLConnection) postUrl.openConnection();
		}
		
		connection.setChunkedStreamingMode(request.getChunkStreamMode());;
		connection.setDoInput(true);
		connection.setUseCaches(false);
		connection.setInstanceFollowRedirects(true);
		connection.setRequestProperty("Accept-Charset", encoding);
		connection.setRequestMethod(request.getMethod());
		if(request.getBody()!=null){
			connection.setRequestProperty("Content-Length", String.valueOf(request.getBody().length));
			connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
		}
		
		if(request.getHeader()!=null){
			fillHeader(request.getHeader(),connection);
		}
		
		//connection.setChunkedStreamingMode(5);
		connection.setConnectTimeout(request.getConnectTimeout());
		connection.setReadTimeout(request.getReadTimeout());
		
		return connection;
	}
	
	private static void fillHeader(Map<String, String> header, HttpURLConnection connection) {
		
		for (Entry<String, String> entry : header.entrySet()) {
			connection.setRequestProperty(entry.getKey(), entry.getValue());
		}
	}
	
	
	/**
	 * 执行
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public Response execute(Request request) throws IOException{
		
		return null;
		
	}
}
